/*
 * Copyright 2011 John Alström
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package se.elva.slticket;

import se.elva.slticket.dialog.InfoDialog;
import se.elva.slticket.price.PriceInfo;
import se.elva.slticket.price.PriceWest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class VastTrafiken extends SmsTicket {

	private double ticketPrice = 0;
	private PriceWest pricePlan;
	private PriceInfo priceInfo = null;
	private final String FULLPRICE = "V";
	private final String TEEN = "S";
	private final String NIGHT = "N";
	private final String ADULTNIGHT = FULLPRICE+NIGHT;
	private final String TEENNIGHT = TEEN+NIGHT;
	private String city = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		pricePlan = new PriceWest();
		setContentView(R.layout.westlayout);
		updateTicketPrice();
		((RadioButton) findViewById(R.id.RadioButtonWestVuxen))
				.setOnCheckedChangeListener(priceChangeListener);
		((RadioButton) findViewById(R.id.RadioButtonWestUngdom))
				.setOnCheckedChangeListener(priceChangeListener);

		((CheckBox) findViewById(R.id.night)).setOnCheckedChangeListener(priceChangeListener);
//		((RadioButton) findViewById(R.id.RadioButtonWestNight))
//				.setOnCheckedChangeListener(priceChangeListener);

		
		((Button) findViewById(R.id.send)).setOnClickListener(mBackListener);
		((Button) findViewById(R.id.cancel))
				.setOnClickListener(mCancelListener);
		setPickCitySpinner();
		
		((Spinner) findViewById(R.id.pickCity))
				.setOnItemSelectedListener(mListener);
		
	}

	private void setPickCitySpinner(){
	    Spinner s = (Spinner) findViewById(R.id.pickCity);
	    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(
	            this, R.array.cityWesttraffic, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s.setAdapter(adapter);

	}
	
	OnItemSelectedListener mListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int which,
				long arg3) {
			String text = "";
			String[] citys = getResources().getStringArray(R.array.cityWesttraffic);
			text = citys[which];
			priceInfo = pricePlan.getPrinceInfo(text);
			city = priceInfo.getCode();
			updateTicketPrice();		
		}
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};
	
	// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
	// = listeners
	// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

	OnCheckedChangeListener priceChangeListener = new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
			updateTicketPrice();
		}
	};


	
	OnClickListener mPickCityListener = new OnClickListener() {
		public void onClick(View v) {
			showDialog(1);
		}
	};

	OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {
			String price = getPrice();
			// "72372"
			if (!"".equals(city) && !"".equals(price)) {
			
				saveState(((Spinner)findViewById(R.id.pickCity)).getSelectedItemPosition());
				sendSms(getPhoneNumer(), city + price, VastTrafiken.this);
			} else {
				showInfoDialog("Fel", getString(R.string.errorZone));
			}
		}
	};

	private void updateTicketPrice() {
		String priceCategory = getPrice();
		if (priceInfo != null) {
			if (priceCategory.equalsIgnoreCase(FULLPRICE)) {
				ticketPrice = priceInfo.getAdult();
			} else if (priceCategory.equalsIgnoreCase(TEEN)) {
				ticketPrice = priceInfo.getTeen();
			} else if (priceCategory.equalsIgnoreCase(ADULTNIGHT)) {
				ticketPrice = priceInfo.getNight();
			}else if (priceCategory.equalsIgnoreCase(TEENNIGHT)) {
				ticketPrice = priceInfo.getNightTeen();
			}
		}
		((TextView) findViewById(R.id.Summa)).setText(getString(
				R.string.ticketPrice).replace(":ticketPrice",
				String.valueOf(ticketPrice)));
		String code = getString(
				R.string.smsInformation);
				code = code.replace(":smsCode",
						String.valueOf(city + priceCategory));
				code = code.replace(":telefon",getPhoneNumer());
		
		((TextView) findViewById(R.id.code)).setText(code);
	}

	private String getPrice() {
		String price = "";
		if (((RadioButton) findViewById(R.id.RadioButtonWestVuxen)).isChecked()) {
			price = FULLPRICE;
		} else if (((RadioButton) findViewById(R.id.RadioButtonWestUngdom))
				.isChecked()) {
			price = TEEN;
		} 
		
		if (((CheckBox) findViewById(R.id.night))
				.isChecked()) {
			price += NIGHT;
		}
		return price;
	}

	@Override
	protected void showInfoDialog(String title, String msg) {
		final InfoDialog info = new InfoDialog(VastTrafiken.this, msg);
		info.show();
	}

	

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == 0) {
			return new AlertDialog.Builder(VastTrafiken.this).setTitle(
					R.string.pickCity).setItems(R.array.city,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							saveChoice = which;
					         Intent intent = findIntentToStart(VastTrafiken.this, which);
				                startActivity(intent);
				                finish();
						}
					}).create();
		} else {
			return new AlertDialog.Builder(VastTrafiken.this).setTitle(
					R.string.pickCity).setItems(R.array.cityWesttraffic,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							//FIXME
						}
					}).create();
		}

	}


	@Override
	protected void onResume() {
		super.onResume();
		setCitySpinner(getState());
		SharedPreferences prefs = getSharedPreferences("SLTicket", 0);
		String restoredText = prefs.getString("saveChoice", null);
		if (restoredText != null) {
			saveChoice = Integer.valueOf(restoredText);
		} else {
			showDialog(0);
		}
	}
	
	private void setCitySpinner(int i){
		((Spinner) findViewById(R.id.pickCity)).setSelection(i);
	}
	
	private void saveState(int i){
		SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
		editor.putInt("latest", i);
		editor.commit();
	}
	
	private int getState(){
		return getPreferences(MODE_WORLD_READABLE).getInt("latest", 0);
	}

	@Override
	public String getPhoneNumer() {
		return getPrefix()+Constans.PHONENUMBER_VASTTRAFIK;
	}

	@Override
	public String getTextToSend() {
		return city+getPrice();
	}

}
